package com.leyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.dto.CategoryDTO;
import com.leyou.entity.Category;
import com.leyou.entity.CategoryBrand;
import com.leyou.mapper.CategoryBrandMapper;
import com.leyou.mapper.CategoryMapper;
import com.leyou.service.CategoryBrandService;
import com.leyou.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    private final CategoryBrandService categoryBrandService;

    public CategoryServiceImpl(CategoryBrandService categoryBrandService){
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public List<CategoryDTO> listCategoryByPid(Long pid) {

        //select * from tb_category where parent_id = #{pid}
        List<Category> categoryList = this.list(new QueryWrapper<Category>().eq("parent_id", pid));

        //List<Category>===>List<CategoryDTO>
        return  CategoryDTO.convertEntityList(categoryList);
    }


    //todo 根据id查询对应的分类信息
    @Override
    public CategoryDTO queryCategoryById(Long id) {
        return new CategoryDTO(this.getById(id));
    }


    //todo 根据id集合查询对应的分类对象集合
    @Override
    public List<CategoryDTO> listCategoryByIds(List<Long> ids) {
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }


    //todo 根据品牌id，查询对应的分类集合
    @Override
    public List<CategoryDTO> listCategoryByBrand(Long bid) {

// todo  1,先访问中间表，根据品牌id，获取，分类id集合；
// todo  2,根据分类id的集合查询分类的集合
        List<Long> categoryIds=this.categoryBrandService
                .query().eq("brand_id",bid)
                .list()
                .stream()
                .map(CategoryBrand::getCategoryId)
                .collect(Collectors.toList());
        return this.listCategoryByIds(categoryIds);
    }
}
